<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true">
        <el-form-item label="">
          <el-input
            style="min-width: 230px"
            v-model="name"
            placeholder="输入内容"
            clearable
            size="small"
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <div class="category">
        <el-tree
          id="category"
          :data="datas"
          draggable
          :props="defaultProps"
          highlight-current
          node-key="id"
          ref="tree"
          default-expand-all
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="() => handleAdd(data)"
              >
              </el-button>
              <el-button
                type="success"
                size="mini"
                icon="el-icon-edit"
                @click="() => handleEdit(node, data)"
              >
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="() => handleDelete(node, data)"
              >
              </el-button>
            </span>
          </span>
        </el-tree>
      </div>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="600px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-form-item label="商品分类" prop="name">
          <el-input
            type="string"
            v-model="form.name"
            placeholder="商品分类"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="上级分类" prop="parent">
          <el-cascader
            ref="parentRef"
            v-model="selectedKeys"
            :options="datas"
            :props="props"
            @change="handleChange"
            clearable
            size="small"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="分类说明" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="分类说明"
            clearable
            size="small"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(false)"
          >保存</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { getParentsPath } from "@/utils/index";
import {
  getCategories,
  addCategory,
  updateCategory,
  delCategory,
} from "@/api/base";

const defaultForm = {
  id: null,
  name: "",
  parent: null,
  path: null,
  remark: "",
};

export default {
  name: "Category",
  components: {
    Pagination,
  },
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        name: [
          {
            type: "string",
            required: true,
            message: "请输入商品分类名称",
            trigger: "blur",
          },
        ],
      },

      tableColumns: [
        {
          key: "id",
          title: "商品编码",
        },
        {
          key: "name",
          title: "商品名称",
        },
        {
          key: "parent",
          title: "上级分类",
        },
        {
          key: "remark",
          title: "类别说明",
        },
      ],

      title: "商品分类",
      dialogVisible: false,
      dialogType: "new",
      datas: [],

      name: "",
      selectedKeys: [],

      defaultProps: {
        children: "children",
        label: "name",
      },

      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },

  created() {
    this.getCategoryList();
  },

  watch: {
    name(val) {
      this.$refs.tree.filter(val);
    },
  },

  methods: {
    getCategoryList() {
      getCategories()
        .then((res) => {
          console.log(res);
          this.datas = res;

        })
        .catch((error) => {
          this.$message.error("获取数据失败!" + error);

        });
    },
    // 查询
    handleFilter() {
      this.getCategoryList();
    },
    // 增加
    handleAdd(data) {
      this.form = Object.assign({}, defaultForm);

      this.selectedKeys = [];
      if (data) {
        this.form.parent = data.id;
      }

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        if (data) {
          this.selectedKeys = getParentsPath(this.form.parent, this.datas);
        }
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(node, data) {
      this.form = data;
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(this.form.parent, this.datas);
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete(node, data) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {

          const res = await delCategory(data.id);
          this.getCategoryList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "fail",
            message: "删除失败!" + err,
          });
        });
    },
    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log(draggingNode, dropNode, dropType);

    },
    handleChange(value) {

      if (this.selectedKeys.length > 0) {
        this.form.parent = this.selectedKeys[this.selectedKeys.length - 1];
        this.form.path = this.selectedKeys.join(",");
      } else {
        this.form.parent = null;
        this.form.path = null;
      }
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";

        let res = null;
        this.form.path = this.selectedKeys.join(",");
        if (isEdit) {
          res = await updateCategory(this.form);
        } else {
          res = await addCategory(this.form);
        }

        this.getCategoryList();

        const { name, parent_name } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
          this.form.parent = this.selectedKeys[this.selectedKeys.length - 1];
          this.form.path = this.selectedKeys.join(",");
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>商品分类: ${name}</div>
              <div>上级分类: ${parent_name}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 10px;
}
.el-cascader {
  width: 100%;
}
</style>